import useCar from '@/utils/car';
const { calculateCarCheckStatus } = useCar();

class Result {
  constructor(message, data = {}) {
    this.message = message
    this.data = data
  }
}

const getStorageItemById = carId => {
  const res = uni.getStorageInfoSync();
  const filterList = res.keys.filter(key => key === `car-${carId}`);
  return filterList[0] ? uni.getStorageSync(filterList[0]) : {}
}

const api = {
  add: (data) => {
    if (!data.id) {
      console.error('车辆add接口参数缺失id')
      return;
    }
    return new Promise((resolve) => {
      uni.setStorageSync(`car-${data.id}`, data);
      resolve(new Result('添加成功'))
    })
  },
  delete: carId => {
    return new Promise((resolve) => {
      uni.removeStorageSync(`car-${carId}`)
      resolve(new Result('删除成功'))
    })
  },
  update: (data) => {
    if (!data.id) {
      console.error('车辆update接口参数缺失id')
      return;
    }
    return new Promise((resolve) => {
      const car = getStorageItemById(data.id);
      uni.setStorageSync(`car-${data.id}`, Object.assign(car, data));
      resolve(new Result('修改成功'))
    })
  },
  detail: carId => {
    return new Promise((resolve) => {
      const car = getStorageItemById(carId);
      if (car.id) {
        const carCheckData = calculateCarCheckStatus(car.registerTime, car.lastCheckTime);
        resolve(new Result('查询成功', Object.assign(car, carCheckData)))
      }else resolve(new Result('查询成功', null))
    })
  },
  getAll: (data = {}) => {
    return new Promise((resolve) => {
      const res = uni.getStorageInfoSync();
      const allCarList = res.keys.filter(key => key.includes('car-')).map(key => {
        const car = uni.getStorageSync(key);
        const carCheckData = calculateCarCheckStatus(car.registerTime, car.lastCheckTime);
        if (data.checkStatus || data.checkStatus === 0) {
          if (carCheckData.checkStatus === data.checkStatus) return Object.assign(car, carCheckData)
          else return null
        }else return Object.assign(car, carCheckData)
      }).filter(item => Boolean(item))
      allCarList.reverse()
      
      // console.log('getAll', allCarList);
      resolve(new Result('查询成功', allCarList))
    })
  },
  identifyDrivingLicense: imgUrl => {
    return new Promise((resolve) => {
      resolve(new Result('识别成功', {
        id: new Date().getTime(),
        licensePlate: `渝B${String(new Date().getTime()).slice(-5)}`,
        carType: '小型汽车',
        owner: '张三',
        useNature: '非营运',
        brandModel: '奥迪',
        identificationCode: '12345678901234567',
        engineCode: '12345678901234567',
        registerTime: '2018-04-23',
        peopleNum: '5',
        casualtyAccident: 0,
        lastCheckTime: '2024-01-23'
      }))
    })
  },
}

export default api
